package ishangchao.cn.haliaeetus.login

import android.os.Bundle
import android.os.CountDownTimer
import android.text.TextUtils
import com.kalemao.library.base.MResponse
import com.kalemao.library.custom.stateful.StatefulLayout
import com.kalemao.library.custom.topbar.KLMTopBarContract.IKLMTopBarView
import com.kalemao.library.http.BaseObserver
import ishangchao.cn.haliaeetus.R
import ishangchao.cn.haliaeetus.base.HaliaeetusActivity
import ishangchao.cn.haliaeetus.databinding.ActGorgetPwdBinding
import ishangchao.cn.haliaeetus.http.HttpNetWork
import ishangchao.cn.haliaeetus.login.event.MessageResetPwd
import org.greenrobot.eventbus.EventBus
import org.jetbrains.anko.textColor
import org.jetbrains.anko.toast
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.util.HashMap

/**
 * @author by dim
 * @data 2018/6/14 17:34
 * 邮箱：271756926@qq.com
 */
class ForgetPwdActivity : HaliaeetusActivity() {
    lateinit var binding: ActGorgetPwdBinding

    override fun getContentViewLayoutID(): Int {
        return R.layout.act_gorget_pwd
    }

    override fun beforeInit() {
        super.beforeInit()
        doesUseDataBanding = true
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        binding = getDataBinding() as ActGorgetPwdBinding
        mStatefullLayout = binding.actForgetStateful

        binding.actForgetTopbar.setKLMTopBarPresent(object : IKLMTopBarView {
            override fun onLeftClick() {
                onBackPressed()
            }

            override fun onRightClick() {

            }

            override fun onRightLeftClick() {

            }
        })

        binding.setMyClick {
            when (it.id) {
                R.id.act_forget_code_get -> {
                    doGetCode()
                }
                R.id.act_forget_forget -> {
                    doChangePwd()
                }
            }

        }
    }

    override fun setStatefulLayout(): StatefulLayout? {
        return if (binding != null) {
            binding.actForgetStateful
        } else null
    }

    private fun doChangePwd() {
        var phone = binding.actForgetPhone.text.toString()
        if (TextUtils.isEmpty(phone)) {
            toast("请先输入手机号")
            return
        }
        var code = binding.actForgetCode.text.toString()
        if (TextUtils.isEmpty(code)) {
            toast("请先输入验证码")
            return
        }
        var pwd = binding.actForgetPwd.text.toString()
        if (TextUtils.isEmpty(pwd)) {
            toast("请先输入密码")
            return
        }
        showLoading()
        var hashMap: HashMap<String, String> = HashMap()
        hashMap["mobile"] = phone
        hashMap["auth_code"] = code
        hashMap["password"] = pwd
        HttpNetWork.getInstance().haliaeetusApi.passwordsReset(hashMap).subscribeOn(Schedulers.io()).observeOn(
                AndroidSchedulers.mainThread()).subscribe(object : BaseObserver<MResponse>() {
            override fun onError(e: Throwable) {
                super.onError(e)
            }

            override fun onNext(mResponse: MResponse) {
                if (mResponse.doesSuccess()) {
                    EventBus.getDefault().post(MessageResetPwd(phone))
                    toast("修改密码成功")
                    this@ForgetPwdActivity.finish()
                } else {
                    toast(mResponse.biz_msg)
                }
                closeLoading()
            }
        })
    }


    private fun doGetCode() {
        var phone = binding.actForgetPhone.text.toString()
        if (TextUtils.isEmpty(phone)) {
            toast("请先输入手机号")
            return
        }
        var hashMap: HashMap<String, String> = HashMap()
        hashMap["mobile"] = phone
        showLoading()
        HttpNetWork.getInstance().haliaeetusApi.smsForgetPwd(hashMap).subscribeOn(Schedulers.io()).observeOn(
                AndroidSchedulers.mainThread()).subscribe(object : BaseObserver<MResponse>() {
            override fun onError(e: Throwable) {
                super.onError(e)
            }

            override fun onNext(mResponse: MResponse) {
                if (mResponse.doesSuccess()) {
                    toast("验证码已发送")
                    doCount()
                } else {
                    toast(mResponse.biz_msg)
                }
                closeLoading()
            }
        })
    }

    private var timer: CountDownTimer? = null

    /**
     * 开始倒计时
     *
     * @author dim.
     * @time 2018/6/15 10:47.
     */
    private fun doCount() {
        /** 倒计时60秒，一次1秒 */
        timer = object : CountDownTimer((60 * 1000).toLong(), 1000) {
            override fun onTick(millisUntilFinished: Long) {
                binding.actForgetCodeGet.text = (String.format("%s秒后重新获取", (millisUntilFinished / 1000)))
                binding.actForgetCodeGet.isClickable = false
                binding.actForgetCodeGet.textColor = resources.getColor(R.color.klm_ccc)
            }

            override fun onFinish() {
                binding.actForgetCodeGet.text = ("获取验证码")
                binding.actForgetCodeGet.isClickable = true
                binding.actForgetCodeGet.textColor = resources.getColor(R.color.blue)
                timer = null
            }
        }.start()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (timer != null) {
            timer!!.cancel()
            timer = null
        }
    }
}